package com.zengdw.logRecord.resolve;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author zengd
 * @date 2021/9/18 14:12
 */
public class LogRecordContext {
    private static final InheritableThreadLocal<Stack<Map<String, Object>>> VARIABLE_MAP_STACK = new InheritableThreadLocal<>();

    public static Map<String, Object> getVariables() {
        return VARIABLE_MAP_STACK.get().peek();
    }

    public static void put(String key, Object value) {
        VARIABLE_MAP_STACK.get().peek().put(key, value);
    }

    public static void putEmptySpan() {
        Stack<Map<String, Object>> stack = VARIABLE_MAP_STACK.get();
        if(stack == null) {
            stack = new Stack<>();
            VARIABLE_MAP_STACK.set(stack);
        }
        stack.push(new HashMap<>());
    }

    public static void clear() {
        Stack<Map<String, Object>> stack = VARIABLE_MAP_STACK.get();
        stack.pop();
        if (stack.isEmpty()) {
            VARIABLE_MAP_STACK.remove();
        }
    }
}
